package com.xujie.chat.server.handler;

import com.esotericsoftware.minlog.Log;
import com.xujie.chat.message.MessageType;
import com.xujie.chat.message.MsgHeader;
import com.xujie.chat.message.MyMessage;
import com.xujie.chat.server.manager.ClientManager;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.ReadTimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.xujie.chat.message.NettyConstant.CLIENT_ID_KEY;

/**
 * 类说明：心跳处理，读超时处理
 *
 * @author Xujie
 * @since 2024/12/28 22:02
 **/
public class HeartBeatHandler extends ChannelInboundHandlerAdapter {
	private final Logger log = LoggerFactory.getLogger(HeartBeatHandler.class);

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		MyMessage message = (MyMessage) msg;
		if (message.getMyHeader() != null && message.getMyHeader().getType() == MessageType.HEARTBEAT_REQ.value()) {
			log.debug("收到心跳请求: {}", message);
			MyMessage buildHeatBeat = buildHeatBeat();
			ctx.writeAndFlush(buildHeatBeat);
			log.debug("发送心跳应答: {}", buildHeatBeat);
		} else {
			ctx.fireChannelRead(msg);
		}
	}

	private MyMessage buildHeatBeat() {
		MyMessage message = new MyMessage();
		message.setMyHeader(new MsgHeader());
		message.getMyHeader().setType(MessageType.HEARTBEAT_RESP.value());
		return message;
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		Log.warn("客户端断开连接：{}", ctx.channel().id().asLongText());
		ClientManager.removeClient(ctx.channel().attr(CLIENT_ID_KEY).get());
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		if (cause instanceof ReadTimeoutException) {
			Log.warn("客户端长时间未通信，可能已经宕机，关闭链路");
			ctx.close();
		}
		super.exceptionCaught(ctx, cause);
	}
}
